package com.ics.web.aspect;

import com.ics.common.annotation.IndexLog;
import com.ics.common.utils.ServletUtils;
import com.ics.common.utils.ip.AddressUtils;
import com.ics.common.utils.ip.IpUtils;
import com.ics.web.controller.travelstar.domain.TbVisitorsLog;
import com.ics.web.controller.travelstar.service.ITbVisitorsLogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * @author shaoly
 * @description
 * @ClassName IndexLogAspect.java
 * @createTime 2024年10月22日 13:39:40
 */
@Aspect
@Component
public class IndexLogAspect {

    @Resource
    private ITbVisitorsLogService logService;

    @Value("${log.open}")
    private boolean logOpen;


    @AfterReturning(pointcut = "@annotation(indexLog)")
    public void handleLog(JoinPoint joinPoint, IndexLog indexLog) {

        if (logOpen) {
            final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            final String ip = IpUtils.getIpAddr();
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            String address = AddressUtils.getRealAddressByIP(ip);

            TbVisitorsLog visitorsLog = new TbVisitorsLog();
            visitorsLog.setLoginIp(ip);
            visitorsLog.setOs(os);
            visitorsLog.setBrowser(browser);
            visitorsLog.setLoginLocation(address);
            visitorsLog.setLoginDateTime(LocalDateTime.now());

            CompletableFuture.runAsync(() -> logService.save(visitorsLog));
        }

    }

}
